<template>
  <div>
    <el-form :inline="true"
             :model="searchForm"
             class="demo-form-inline">
      <el-form-item label="用户名称">
        <el-input v-model="searchForm.username"
                  clearable
                  placeholder="用户名称"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary"
                   @click="getUserList">查询</el-button>
        <el-button type="success"
                   @click="addHandle()"
                   v-if="hasAuth('sys:user:save')">新增</el-button>
        <el-popconfirm title="确定要删除这条记录吗？"
                       v-if="hasAuth('sys:user:delete')"
                       @confirm="delHandle(null)">
          <el-button type="danger"
                     :disabled="buttonDisable"
                     slot="reference">批量删除</el-button>
        </el-popconfirm>
      </el-form-item>
    </el-form>
    <el-table :data="tableData"
              border
              stripe
              tooltip-effect="dark"
              style="width: 100%"
              @selection-change="handleSelectionChange">
      <el-table-column type="selection"
                       width="55"> </el-table-column>
      <el-table-column label="头像"
                       width="50"> <template slot-scope="scope">
          <el-avatar size="small"
                     :src="scope.row.avatar"></el-avatar>
        </template> </el-table-column>
      <el-table-column prop="username"
                       label="用户名"
                       width="120"> </el-table-column>
      <el-table-column label="角色名称"
                       width="180"> <template slot-scope="scope">
          <el-tag style="margin-right: 5px;"
                  size="small"
                  type="info"
                  v-for="(item,index) in scope.row.roles"
                  :key="index">{{item.name}}</el-tag>
        </template> </el-table-column>
      <el-table-column prop="email"
                       label="邮箱"> 
                       </el-table-column>
      <el-table-column prop="phone"
                       label="手机号"> </el-table-column>
      <el-table-column label="状态"> <template slot-scope="scope">
          <el-tag v-if="scope.row.statu === 0"
                  size="small"
                  type="danger">禁用</el-tag>
          <el-tag v-else-if="scope.row.statu === 1"
                  size="small"
                  type="success">正常</el-tag>
        </template> </el-table-column>
      <el-table-column prop="created"
                       label="创建时间"
                       width="200"> </el-table-column>
      <el-table-column width="260px"
                       label="操作"> <template slot-scope="scope">
          <el-button type="text"
                     @click="roleHandle(scope.row.id)"
                     v-if="hasAuth('sys:user:role')">分配角色</el-button>
          <el-divider direction="vertical"></el-divider>
          <el-button type="text"
                     @click="repassHandle(scope.row.id, scope.row.username)"
                     v-if="hasAuth('sys:user:repass')">重置密码</el-button>
          <el-divider direction="vertical"></el-divider>
          <el-button type="text"
                     @click="editHandle(scope.row.id)"
                     v-if="hasAuth('sys:user:update')">编辑</el-button>
          <el-divider direction="vertical"></el-divider>
          <el-popconfirm title="确定要删除这条记录吗？"
                         @confirm="delHandle(scope.row.id)"
                         v-if="hasAuth('sys:user:delete')">
            <el-button type="text"
                       slot="reference">删除</el-button>
          </el-popconfirm>
        </template> </el-table-column>
    </el-table>

    <el-pagination @size-change="handleSizeChange"
                   @current-change="handleCurrentChange"
                   :current-page="currentPage"
                   :page-sizes="[10, 20, 50, 100]"
                   :page-size="PageSize"
                   layout="total, sizes, prev, pager, next, jumper"
                   :total="total">
    </el-pagination>

    <el-dialog title="用户信息"
               :visible.sync="dialogFormVisible"
               width="600px">
      <el-form :model="editForm"
               :rules="editFormRules"
               ref="editForm">
        <el-form-item label="用户名"
                      prop="username"
                      label-width="100px">
          <el-input v-model="editForm.username"
                    autocomplete="off"></el-input>
          <el-alert title="初始密码为888888"
                    :closable="false"
                    type="info"
                    style="line-height: 12px;"></el-alert>
        </el-form-item>
        <el-form-item label="邮箱"
                      prop="email"
                      label-width="100px">
          <el-input v-model="editForm.email"
                    autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="手机号"
                      prop="phone"
                      label-width="100px">
          <el-input v-model="editForm.phone"
                    autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="状态"
                      prop="statu"
                      label-width="100px">
          <el-radio-group v-model="editForm.statu">
            <el-radio :label="0">禁用</el-radio>
            <el-radio :label="1">正常</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer"
           class="dialog-footer">
        <el-button @click="closeEdit">取 消</el-button>
        <el-button type="primary"
                   @click="submitEditForm('editForm')">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 分配权限 -->
    <el-dialog title="角色信息"
               :visible.sync="dialogRolesVisible"
               width="600px"
               @closed="resetPernForm()">
      <el-form :model="rolesForm"
               ref="rolesForm">
        <el-tree :data="rolesTreeData"
                 ref="rolesTree"
                 show-checkbox
                 node-key="id"
                 :default-expand-all="true"
                 check-strictly
                 :default-expanded-keys="[2, 3]"
                 :default-checked-keys="[5]"
                 :props="defaultProps">
        </el-tree>

      </el-form>
      <div slot="footer"
           class="dialog-footer">
        <el-button @click="resetPernForm()">取 消</el-button>
        <el-button type="primary"
                   @click="submitRolesForm()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
export default {
  name: 'User',
  components: {},
  props: {},
  data() {
    return {
      PageSize: null,
      total: 1,
      currentPage: 1,
      searchForm: {},
      selectedIds: [],
      buttonDisable: true,
      tableData: [],
      /* 编辑弹框 */
      dialogFormVisible: false,
      editForm: {},
      editFormRules: {
        username: [
          { required: true, message: '请输入用户名称', trigger: 'blur' },
        ],
        email: [{ required: true, message: '请输入邮箱', trigger: 'blur' }],
        statu: [{ required: true, message: '请选择状态', trigger: 'blur' }],
      },
      /* 分配权限弹框 */
      dialogRolesVisible: false,
      rolesForm: {},
      rolesTreeData: [],
      defaultProps: {
        children: 'children',
        label: 'name',
      },
    }
  },
  created() {
    this.getUserList()
    this.getRolesTreeData()
  },
  methods: {
    repassHandle(id, username) {
      this.$confirm('将重置用户【' + username + '】的密码, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        this.$axios.post('/sys/user/repass?id=' + id).then((res) => {
          this.$message({
            showClose: true,
            message: '恭喜你，操作成功',
            type: 'success',
            onClose: () => {},
          })
        })
      })
    },
    getUserList() {
      this.$axios
        .get('/sys/user/list', {
          params: {
            name: this.searchForm.username,
            size: this.PageSize,
            current: this.current,
          },
        })
        .then((res) => {
          this.tableData = res.data.data.records
          this.total = res.data.data.total
          this.PageSize = res.data.data.size
          this.current = res.data.data.current
        })
    },
    getRolesTreeData() {
      this.$axios.get('/sys/role/list').then((res) => {
        this.rolesTreeData = res.data.data.records
      })
    },
    batchRemove() {},
    search() {},
    handleSelectionChange(selectRows) {
      this.selectedIds = selectRows.map((row) => {
        return row.id
      })
      this.buttonDisable = this.selectedIds.length > 0 ? false : true
    },
    handleSizeChange(newSize) {
      this.PageSize = newSize
      this.getUserList()
    },
    handleCurrentChange(newCurrent) {
      this.current = newCurrent
      this.getUserList()
    },
    /* 编辑弹窗方法 */
    closeEdit(formName) {
      this.$refs.editForm.resetFields()
      this.editForm = {}
      this.dialogFormVisible = false
    },
    addHandle() {
      this.editForm = {}
      this.dialogFormVisible = true
    },
    editHandle(id) {
      this.$axios.get('/sys/user/detail/' + id).then((res) => {
        this.editForm = res.data.data
        this.dialogFormVisible = true
      })
    },
    submitEditForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$axios
            .post(
              '/sys/user/' + (this.editForm.id ? 'edit' : 'save'),
              this.editForm
            )
            .then((res) => {
              if(res && res.msg) {
                this.$message({
                  message: res.msg,
                  type: 'warning'
                });
              }
              this.closeEdit(formName)
              this.getUserList()
              this.$message({
                showClose: true,
                message: '更新成功',
                type: 'success',
                onClose: () => {},
              })
            })
        } else {
          return false
        }
      })
    },
    delHandle(id) {
      let rIds = []
      if (id) {
        rIds.push(id)
      } else {
        rIds = this.selectedIds
      }
      this.$axios
        .delete('/sys/user/remove', {
          data: JSON.stringify(rIds),

        })
        .then((res) => {
          this.$message.success('删除成功')
          this.getUserList()
        })
    },
    /* 分配权限弹窗方法 */
    roleHandle(id) {
      this.dialogRolesVisible = true
      this.$axios.get('/sys/user/detail/' + id).then((res) => {
        let roleIds = res.data.data.roles.map((role) => {
          return role.id
        })
        this.$refs.rolesTree.setCheckedKeys(roleIds)
        this.rolesForm = res.data.data
      })
    },
    submitRolesForm(formName) {
      let menuIds = this.$refs.rolesTree.getCheckedKeys()
      this.$axios
        .post('/sys/user/permRoles/' + this.rolesForm.id, menuIds)
        .then((res) => {
          this.resetPernForm()
          this.getUserList()
          this.$message({
            showClose: true,
            message: '更新成功',
            type: 'success',
            onClose: () => {},
          })
        })
    },
    resetPernForm() {
      this.$refs.rolesTree.setCheckedKeys([])
      this.dialogRolesVisible = false
    },
  },
  watch: {},
  computed: {},
  mounted() {},
}
</script>
<style scoped>
.el-pagination {
  float: right;
  margin-top: 22px;
}
</style>